<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\library\Auth;
use app\admin\model\personal\AccountLog;
use app\admin\model\finance\FinanceLog;
use app\admin\controller\vxpay\Pay;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Gold extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\order\Order
     */
    protected $model = null;
    protected $goods_model = null;
    protected $personal_model = null;
    protected $noNeedRight = ['getAmount'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Gold();
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->goods_model = new \app\admin\model\goods\Goods();
        $this->personal_model = new \app\admin\model\personal\Personal();

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $auth = Auth::instance();
            $id = $auth->id;
            //获取客服类型
            $ke_type = \app\admin\model\Admin::where(['id'=>$id])->value('type');
            //客服类型1全部2手游3端游
            if($ke_type == 2){
                //根据平台区分端游手游  手游有平台 端游无平台
                $con['goods.plat_id'] = ['neq',0];
            }elseif($ke_type == 3){
                //根据平台区分端游手游  手游有平台 端游无平台
                $con['goods.plat_id'] = ['eq',0];
            }else{
                $con = [];
            }
			$start_time = strtotime(date("Y-m-d"),time());
            $end_time = $start_time + 86400;

            $countAll = $this->model
                ->where(['order_class_type'=>2,'ontime'=>['between',[$start_time,$end_time]]])
                ->count();

            $filter = json_decode($this->request->get('filter'),true);
            if(isset($filter['overtime'])){
                $search_over_time = explode(' - ',$filter['overtime']);
                $countFinish = $this->model
                    ->where(['order_class_type'=>2,'status'=>5,'overtime'=>['between',[strtotime($search_over_time[0]),strtotime($search_over_time[1])]]])
                    ->field('count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(fee)  is null then 0 else sum(fee) end as priceSall')
                    ->find();
				$kuaqu_list = $this->model
                    ->where(['order_class_type'=>2,'status'=>5,'game_id'=>2,'overtime'=>['between',[strtotime($search_over_time[0]),strtotime($search_over_time[1])]]])
                    ->field('cross_id,count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(price)  is null then 0 else sum(price) end as priceSall')
                    ->group('cross_id')
                    ->select();
            }else{
                $countFinish = $this->model
                    ->where(['order_class_type'=>2,'status'=>5,'overtime'=>['between',[$start_time,$end_time]]])
                    ->field('count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(fee)  is null then 0 else sum(fee) end as priceSall')
                    ->find();
				$kuaqu_list = $this->model
                    ->where(['order_class_type'=>2,'status'=>5,'game_id'=>2,'overtime'=>['between',[$start_time,$end_time]]])
                    ->field('cross_id,count(*) as count,case when sum(amount) is null then 0 else sum(amount) end as priceAll,case when sum(price)  is null then 0 else sum(price) end as priceSall')
                    ->group('cross_id')
                    ->select();
            }
			
			$kuaqu_list_temp = array_column($kuaqu_list,null,'cross_id');
            $kuaqu = array();
            for($i=1;$i<=9;$i++){
                if(isset($kuaqu_list_temp[$i])){
                    $kuaqu[$i]['num'] = $kuaqu_list_temp[$i]['count'];
                    $kuaqu[$i]['price'] = $kuaqu_list_temp[$i]['priceAll'];
                }else{
                    $kuaqu[$i]['num'] = 0;
                    $kuaqu[$i]['price'] = 0;
                }
            }
            $countCancel = $this->model
                ->where(['order_class_type'=>2,'overtime'=>['between',[$start_time,$end_time]],'status'=>['in',['7','9']]])
                ->count();
            $op['gold.status'] = ['not in',[30,31]];
            $list = $this->model
                ->with(['goods','personal','admin'])
                ->where($where)
                ->where($con)
                ->where('order_class_type','neq',1)
                ->where($op)
		        ->field('gold.status,order_class_type,goods.prices')
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['true','fee','daifa_fee','id','order_class_type','cross','account','order_sn','game','payway','plat','area','server','type_name','deposit','buy_type','invite','title','price','prices','num','amount','ontime','paytime','overtime','status','complaint']);
                $row->visible(['personal']);
                $row->getRelation('personal')->visible(['account','mobile']);
                $row->visible(['admin']);
                $row->getRelation('admin')->visible(['username']);
            }
            foreach($list as $k => $v){
                $goods = Db::name('goods')->where(['id'=>$v['goods_id']])->field('is_safe,goods_class_type,method')->find();
                $goods_total_price = round($v['prices']*$v['num'],2);
				// if($v['id'] > 2187){
                    $list[$k]['true'] = round($goods_total_price - $v['fee'],2);
                // }else{
                //     $fee_info = $this->getAmount($goods_total_price, $goods['goods_class_type'], $goods['is_safe'], $v['xyg'], $goods['method'],$v['game_id'],$v['goods_type'],$v['fee'],$v['daifa_fee']);
                //     $service = round($fee_info['fee']<1?1:$fee_info['fee'],2);
                //     $list[$k]['true'] = round($goods_total_price - $service,2);
                //     $list[$k]['fee'] = $service;
                //     $list[$k]['daifa_fee'] = round($v['xyg']=='1'?0:$fee_info['daifa_fee'],2);
                // }
                if($list[$k]['daifa_fee'] < 1) $list[$k]['daifa_fee'] = 1;
				$list[$k]['title'] = mb_substr($v['title'],0,60);
            }

            $result = array("total" => $list->total(),"rows" => $list->items(),"extend" => ['stat1' => $countAll, 'stat2' => $countFinish['count'],'stat3'=>$countCancel,'stat4'=>$countFinish['priceAll'],'stat5'=>round($countFinish['priceSall'],2)],'cross'=>$kuaqu);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['goods'] = $this->goods_model::where('id', '=', $row['goods_id'])->find();
        $row['personal'] = $this->personal_model::where('id', '=', $row['uid'])
            ->field('account,is_real,id_card,name')->find();
        $row['role_server'] = Db::name('game_info')->where('id',$row['role_server'])->value('name');
        $sku = htmlspecialchars_decode($row['goods']['sku']);

        $sku = json_decode($sku,true);
        // dump($sku);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("sku", $sku);
        return $this->view->fetch();
    }


    /**
     * 订单管控
     */
    public function manage($ids = null)
    {
        $row = $this->model->get($ids);
        $goods = Db::name('goods')->where(['id'=>$row['goods_id']])->field('is_safe,goods_class_type,method')->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['status'] == 7){
                        if($row['status'] == 7){
                            $this->error('订单已撤单');
                        }
                        //买家原因撤单 订单重新上架（即同金币一样退库存） 卖家原因撤单 商品直接下架
                        if($params['away'] == 2){
                            //卖家  商品下架
                            Db::name('goods')->where('id',$row['goods_id'])->update(['status'=>5]);
                        }
                        //商品库存退回
                        Db::name('goods')->where('id',$row['goods_id'])->setInc('stock',$row['num']);
                        //取消订单，资金退回余额
                        $id = 1988;
                        $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
                        $sn = date('Yhis') . $rand;
                        $id = str_pad($id, (18 - strlen($sn)), '0', STR_PAD_BOTH);
                        $refund_sn = $sn . $id;
                        $root_path = $this->request->root(true);
                        if($row['payway'] == '微信'){
                            // $refund_url = str_replace('/BfcTyWlLqd.php','',$root_path).'/api/pay/notify_wechat_refund';
                            // $epay = \addons\epay\library\Service::refund_wechat('0.1',$row['order_sn'],$refund_sn,'wechat','退款',$refund_url,'','app');
                            // $params['status'] = $row['status'];
                            $vxpay = new Pay();
                            $result = $vxpay->refund($row['order_sn'],$row['amount'],$row['amount']);
                            $refund_arr = array(
                                'type'=>'微信',
                                'order_no'=>$row['order_sn'],
                                'created_time'=>date("Y-m-d H:i:s",time()),
                                'status'=>$result['result_code'],
                                'content'=>json_encode($result,JSON_UNESCAPED_UNICODE),
                            );
                            DB::name("refund_log")->insert($refund_arr);
                            $log = new AccountLog();
                            $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '后台客服撤单', 1,'',1);
                        }else if($row['payway'] == '支付宝'){
                            $epay = \addons\epay\library\Service::refund_ali('0.1',$row['order_sn'],$refund_sn,'alipay','退款','','','app');
                            if($epay['code'] == 10000){
                                $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                                $log = new AccountLog();
                                $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '后台客服撤单', 1,'',1);
                            }else{
                                $this->error("支付宝退款异常，请联系技术人员查看");
                            }
                        }else {
                            //取消订单，资金退回余额
                            $uinfo = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                            $log = new AccountLog();
                            $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '后台客服撤单', 1,'',1);
                            if ($res !== false) {
                                Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'balance', $row['amount'] );
                            }
                            $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
                            // dump($uinfo);
                            $financelog = new FinanceLog();
                            $financelog->addFinanceLog($row['buyid'],'后台客服撤单',$uinfo['balance'],$uinfo['jy_balance'], $row['amount'], $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['reason']);
                        }
                    }

                    if($params['status'] == 5){
                        if($row['status'] == 5){
                            $this->error('订单已完成');
                        }
                        //已完成的订单给卖家到账
                        $log = new AccountLog();
                        // 心意购延迟3天 （取消）
                        // 没有心意购实时到账
                        // if($row['xyg']==2){
                        //     $arrivaltime = 3*24*60*60;
                        //     $log->addAccountLog($row['uid'], '+'.$row['amount'], 2, '售得', 0,$arrivaltime);
                        // }else{
                        $fee_info = $this->getAmount($row['amount'], $goods['goods_class_type'], $goods['is_safe'], $row['xyg'], $goods['method'],$row['game_id'],$row['goods_type'],'','');
                        //$money = $fee_info['fee'] + $row['amount'];
						$money = $row['amount'] - $fee_info['fee'];
						$res = $log->addAccountLog($row['uid'], '+'.$money, 2, '售得', 1,'');
                        // dump($res);exit;
                        if ($res !== false) {
                            $uinfo = $this->personal_model->where(['id'=>$row['uid']])->field('balance,jy_balance')->find();
                            //用户余额增加
                            Db::name('personal')->where(['id'=>$row['uid']])->setInc( 'balance', $money );
                            $uinfo_after = $this->personal_model->where(['id'=>$row['uid']])->field('balance,jy_balance')->find();
                            // dump($uinfo);
                            $financelog = new FinanceLog();
                            $financelog->addFinanceLog($row['uid'],'售得',$uinfo['balance'],$uinfo['jy_balance'], $money, $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['reason']);
                        }
                        $params['overtime'] = time();
                        // }
                        
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 查看聊天记录 add version
     */
    public function chat($ids = null)
    {
        $row = $this->model::where('id', '=', $ids)->field('id,order_sn,uid,buyid')->find();
        $list = DB::name('timely')->where(['order_sn'=>$row['order_sn']])->select();
        if($list){
            foreach($list as $k=>$v){
                if(strpos($v['content'],'https://780g.oss-cn-zhangjiakou.aliyuncs.com') !== false){
                    //消息内容为图片
                    $list[$k]['c_type'] = 1;
                }else{
                    //消息内容为文字
                    $list[$k]['c_type'] = 2;
                }
                if($v['fromUserId']==$row['buyid']){
                    $list[$k]['title'] = '买家';
                    $list[$k]['type'] = 1;
                }else{
                    $list[$k]['title'] = '卖家';
                    $list[$k]['type'] = 2;
                }
            }
        }
        $this->view->assign([
            "list" => $list,
            "row" => $row,
        ]);
        return $this->view->fetch(); 
    }

    /**
     * 客服联系买/卖家
     */
    public function online($ids = null)
    {
        $row = $this->model::where('id', '=', $ids)->field('order_sn,id,uid,buyid')->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

	/*
    public function getAmount($amount, $type, $safe, $xyg, $method)
    {
        $map['type'] = $type;
        $map['safe'] = $safe;
        $map['xyg'] = $xyg;
        $map['method'] = $method;
        $fee = Db::name('server')->where($map)->find();
        $trade = $amount * $fee['trade'];
        if($trade < 1){
            $amount = $amount - 1;
        }else{
            $amount = $amount * (1-$fee['trade']);
        }
        return round($amount,2);
    }*/
	public function getAmount($amount, $type, $safe, $xyg, $method, $game_id, $game_type, $fee_a,$daifa_fee)
    {
        $map['safe'] = $safe;
        $map['type'] = $type;
        //$map['xyg'] = $xyg;
        $map['method'] = $method;
        $map['game_id'] = $game_id;
        $map['game_type'] = $game_type;
        if(!$fee_a){
            $fee = Db::name('server')->where($map)->find();
            if(!$fee){
                $fee = DB::name("server")->where('id',11)->find();
            }
            $fee_a = $fee['trade']*$amount;
        }else{
            $fee_a = $fee_a*$amount;
        }
        $daifa = 0;
        if($daifa_fee == 0){
            $fee = Db::name('server')->where($map)->find();
            if(!$fee){
                $fee = DB::name("server")->where('id',10)->find();
            }
            $daifa = $amount * $fee['service'];
        }else{
            $daifa = $amount*$daifa_fee;
        }

        return ['fee'=>$fee_a,'daifa_fee'=>$daifa];
    }


}
